﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

using JetBlack.SimpleTopicBus.Messages;
using JetBlack.SimpleTopicBus.Adapters;
using System.Net;

namespace ExampleSubscriber
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a client.
            Client client = new Client();

            try
            {
                // Assume the Distributor is running on the local machine.
                client.Connect(Dns.GetHostName(), 9121);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to connect to distributor: {0}", ex.Message);
                Environment.Exit(-1);
            }

            // Add a delegate to be called should the client be closed.
            client.OnClosed += OnClosed;
            // Add a delegate to be called when data arrives.
            client.OnData += OnData;

            // Subscribe to some topics.
            client.AddSubscription("LSE.VOD");
            client.AddSubscription("LSE.TSCO");
            client.AddSubscription("LSE.FOO");
            client.AddSubscription("VTX.BAY");

            // Wait to exit.
            Console.WriteLine("Press <enter> to quit");
            Console.ReadLine();

            // Tidy up.
            client.Close();
        }

        static void OnClosed(bool isAbnormal)
        {
            Console.WriteLine("This client as closed {0}", isAbnormal ? "abnormally" : "normally");
            if (isAbnormal)
                Environment.Exit(-1);
        }

        static void OnData(string topic, IDictionary<string, object> data, bool isImage)
        {
            // Write out the data received. Note the message may be empty.
            Console.WriteLine("OnData: {0} {1}", topic, isImage);
            if (data == null)
                Console.WriteLine("No Data");
            else
            {
                foreach (KeyValuePair<string, object> pair in data)
                    Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
            }
        }
    }
}
